#!/usr/bin/env python

"""
Usage: hdvb-to-myth HDVB_CHANS.SQLITE

Outputs a MySQL script to stdout which allocates LCNs to mythtv's database.
"""

from __future__ import print_function

import sqlite3
import sys

def load_from_sqlite(filename):
    conn = sqlite3.connect(filename)
    curs = conn.cursor()
    curs.execute("SELECT service_id, ts_id, lcn FROM services ORDER BY lcn")
    d = {}
    for row in curs.fetchall():
        d[int(row[2])] = [ int(row[0]), row[1] ]
    curs.close()
    conn.close()
    return d


def print_chans(chans):
    items = chans.items()
    items.sort(key = lambda x: x[0])
    for i in items:
        print("UPDATE channel SET channum = %d "
                "WHERE serviceid = %d AND mplexid = " \
                "(SELECT mplexid FROM dtv_multiplex WHERE transportid = %d);" %
                (i[0], i[1][0], i[1][1]))


def print_extras():
    print()
    print("-- No adverts in BBC")
    print("UPDATE channel set commmethod=-2 " \
            "WHERE name LIKE '%BBC%' OR name LIKE 'CBeebies%';")
    print("-- Default channel setting")
    print("UPDATE settings SET data = " \
            "(SELECT channum FROM channel ORDER BY channum ASC LIMIT 1) " \
            "WHERE value='DefaultTVChannel';")

chans = load_from_sqlite(sys.argv[1])
print("USE mythconverg;")
print_chans(chans)
print_extras()
